<template>
	<div>
		<el-dialog :show-close="false" :close-on-click-modal="false" title="选点配置" center :visible.sync="visible"
			fullscreen @close="dialogClose('distForm')">
			<div slot="title" class="check-dialog-title-box">
				选点配置
				<div class="check-dialog-close-btn flex justify-end align-center flex-no-wrap">
					<el-button icon="el-icon-circle-close" size="small" type="primary"
						@click.native="dialogClose('distForm')">关闭</el-button>
				</div>
			</div>
			<el-form ref="distForm" :model="distForm" label-width="85px" center size="mini">
				<el-card class="box-card margin-bottom-sm" shadow="never">
					<el-row class="margin-right" :gutter="10">
						<el-col :span="8">
							<el-col :span="24" v-show="hasDateRange">
								<el-form-item label="时间段">
									<el-date-picker clearable v-model="distForm.date_range" type="daterange"
										range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
										format="yyyy年MM月dd日" value-format="yyyy-MM-dd HH:mm:ss"
										:default-time="['00:00:00', '23:59:59']" style="width:100%" disabled>
									</el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item>
									<div slot="label">需要分配<br /><span v-show="distForm.dist_type==1"
											class="text-xs text-red"
											style="font-weight: normal;">总数:{{dist_all_sum}}</span></div>
									<el-row>
										<el-col :span="24" v-show="show_dist_type && hasCombo">
											<el-form-item>
												<el-radio-group v-model="distForm.dist_type" @change="changeDistType">
													<el-radio-button :label="1">数量</el-radio-button>
													<el-radio-button :label="2">套餐</el-radio-button>
												</el-radio-group>
											</el-form-item>
										</el-col>
										<el-col :span="24" v-if="distForm.dist_type==1">
											<el-card class="box-card margin-bottom-sm point-all-card" shadow="never"
												v-if="point_types_dianti && point_types_dianti.length > 0 && distForm.all_points_num[item.id]>0"
												v-for="item in point_types_dianti" :key="item.id">
												<el-form-item :label="item.name">
													<el-col :span="24">
														<el-input v-model="distForm.all[item.id]" type="number" min="0"
															@input="(val) => changePointAll(val, item.id)">
															<template slot="append">点位</template>
														</el-input>
													</el-col>
												</el-form-item>
												<el-form-item label="一层一个" v-if="hasOneLimt">
													<el-col :span="24">
														<el-radio-group v-model="distForm.one_limit[item.id]">
															<el-radio :label="true">是</el-radio>
															<el-radio :label="false">否</el-radio>
														</el-radio-group>
													</el-col>
												</el-form-item>
												<el-form-item label="楼层限制"
													v-if="hasFloorLimt && (item.id == 123 || item.id == 125)">
													<el-col :span="24">
														<el-radio-group v-model="distForm.floor_limit[item.id]">
															<el-radio :label="1">无</el-radio>
															<el-radio :label="2">地上</el-radio>
															<el-radio :label="3">地下</el-radio>
														</el-radio-group>
													</el-col>
												</el-form-item>
											</el-card>
										</el-col>
										<el-col :span="24" v-if="distForm.dist_type==1">
											<el-card class="box-card margin-bottom-sm point-all-card" shadow="never"
												v-if="point_types_churukou && point_types_churukou.length > 0 && distForm.all_points_num[item.id]>0"
												v-for="item in point_types_churukou" :key="item.id">
												<el-form-item :label="item.name">
													<el-col :span="24">
														<el-input v-model="distForm.all[item.id]" type="number" min="0"
															@input="(val) => changePointAll(val, item.id)">
															<template slot="append">点位</template>
														</el-input>
													</el-col>
												</el-form-item>
											</el-card>
										</el-col>
										<el-col :span="24" v-if="distForm.dist_type==2">
											<el-card class="box-card margin-bottom-sm point-all-card" shadow="never"
												v-for="item in active_combo_list" :key="item.id">
												<el-form-item :label="item.name+(item.code?('('+item.code+')'):'')">
													<el-col :span="24">
														<el-input v-model="distForm.all_combo[item.id]" type="number"
															min="0" @input="(val) => changePointAllCombo(val, item.id)">
															<template slot="append">个</template>
														</el-input>
													</el-col>
													<el-col :span="24">
														<div v-for="(r,i) in item.ruleList" :key="r.id"
															class="margin-lr-xs margin-tb-xxs combo-rule">{{r.desp}}
														</div>
													</el-col>
												</el-form-item>
											</el-card>
										</el-col>
									</el-row>
								</el-form-item>
							</el-col>
						</el-col>
						<el-col :span="16">
							<el-col :span="24">
								<el-form-item label="分配规则">
									<el-radio-group v-model="distForm.distribute_type" size="mini"
										@change="(val) => changeDistributeType(val)">
										<el-radio label="平均分配">平均分配</el-radio>
										<el-radio label="高均价优先" disabled>高均价优先</el-radio>
										<el-radio label="高上刊率优先" disabled>高上刊率优先</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item label="分配数量">
									<el-table :data="distForm.building_areas" stripe size="mini"
										style="width: 100%;margin-top:0;" border
										:summary-method="(param) => getRemain(param)" show-summary>
										<el-table-column prop="name" label="楼盘名称" align="center" min-width="140"
											fixed="left" show-overflow-tooltip></el-table-column>
										<!-- <el-table-column prop="all_unit" label="单元总数" align="center" width="80"
											show-overflow-tooltip></el-table-column> -->
										<template v-if="distForm.dist_type==2 && (distForm.all_combo[item.id] || 0) > 0"
											v-for="item in active_combo_list">
											<el-table-column :index="item.id" :label="item.name"
												:prop="'combo_'+item.id" align="center" show-overflow-tooltip
												min-width="130">
												<template slot-scope="scope">
													<div class="flex flex-no-wrap justify-center align-center">
														<el-input v-model="distForm.to_combo[scope.row.id+'_'+item.id]"
															type="number" :min="0" size="mini" style="width: 80px"
															@input="changePointToCombo($event, scope.row.id, item.id)" />
													</div>
												</template>
											</el-table-column>
										</template>
										<template
											v-if="point_types_dianti && point_types_dianti.length > 0 && (distForm.all[item.id] || 0) > 0"
											v-for="item in point_types_dianti">
											<el-table-column :index="item.id" :label="item.name" align="center"
												show-overflow-tooltip min-width="270">
												<template slot-scope="scope">
													<div class="flex flex-no-wrap justify-center align-center">
														<div class="margin-right-xs text-bold">
															总:{{distForm.points_num[scope.row.id+'_'+item.id] || 0}}
														</div>
														<el-input v-model="distForm.to[scope.row.id+'_'+item.id]"
															type="number"
															:min="(distForm.to_exact[scope.row.id+'_'+item.id] || []).length"
															size="mini" style="width: 170px"
															:disabled="distForm.dist_type==2">
															<template
																slot="append">/{{distForm.can[scope.row.id+'_'+item.id] || 0}}</template>
														</el-input>
														<div
															:class="['margin-left-xs', ((distForm.can[scope.row.id+'_'+item.id] || 0) - (distForm.to[scope.row.id+'_'+item.id] || 0))>0?'':(
															((distForm.can[scope.row.id+'_'+item.id] || 0) - (distForm.to[scope.row.id+'_'+item.id] || 0))==0?'text-green':'text-red')]">
															{{((distForm.can[scope.row.id+'_'+item.id] || 0) - (distForm.to[scope.row.id+'_'+item.id] || 0)) > 0 ? 
															('余:'+((distForm.can[scope.row.id+'_'+item.id] || 0) - (distForm.to[scope.row.id+'_'+item.id] || 0))) : 
															(((distForm.can[scope.row.id+'_'+item.id] || 0) - (distForm.to[scope.row.id+'_'+item.id] || 0)) == 0 ? 
															'满' : '超:'+((distForm.to[scope.row.id+'_'+item.id] || 0) - (distForm.can[scope.row.id+'_'+item.id] || 0)))}}
														</div>
														<div v-show="hasExact"
															class="flex flex-direction justify-center align-center flex-no-wrap text-center margin-lr xs">
															<el-button @click.native="onExact(scope.row.id,item.id)"
																type="text" class="exact-btn">精准选点<span
																	v-if="(distForm.to_exact[scope.row.id+'_'+item.id] || []).length>0">({{(distForm.to_exact[scope.row.id+'_'+item.id] || []).length}})</span>
															</el-button>
															<el-button
																@click.native="onClearExact(scope.row.id,item.id)"
																type="text" class="text-red exact-btn"
																v-if="(distForm.to_exact[scope.row.id+'_'+item.id] || []).length>0">
																清空</el-button>
														</div>
													</div>
												</template>
											</el-table-column>
										</template>
										<!-- <el-table-column prop="all_door" label="大门总数" align="center" width="80"
											show-overflow-tooltip></el-table-column> -->
										<template
											v-if="point_types_churukou && point_types_churukou.length > 0 && (distForm.all[item.id] || 0) > 0"
											v-for="item in point_types_churukou">
											<el-table-column :index="item.id" :label="item.name" align="center"
												show-overflow-tooltip min-width="270">
												<template slot-scope="scope">
													<div class="flex flex-no-wrap justify-center align-center">
														<div class="margin-right-xs">
															总:{{distForm.points_num[scope.row.id+'_'+item.id] || 0}}
														</div>
														<el-input v-model="distForm.to[scope.row.id+'_'+item.id]"
															type="number"
															:min="(distForm.to_exact[scope.row.id+'_'+item.id] || []).length"
															size="mini" style="width: 170px"
															:disabled="distForm.dist_type==2">
															<template
																slot="append">/{{distForm.can[scope.row.id+'_'+item.id] || 0}}</template>
														</el-input>
														<div
															:class="['margin-left-xs', ((distForm.can[scope.row.id+'_'+item.id] || 0) - (distForm.to[scope.row.id+'_'+item.id] || 0))>0?'':(
															((distForm.can[scope.row.id+'_'+item.id] || 0) - (distForm.to[scope.row.id+'_'+item.id] || 0))==0?'text-green':'text-red')]">
															{{((distForm.can[scope.row.id+'_'+item.id] || 0) - (distForm.to[scope.row.id+'_'+item.id] || 0)) > 0 ?
															('余:'+((distForm.can[scope.row.id+'_'+item.id] || 0) - (distForm.to[scope.row.id+'_'+item.id] || 0))) : 
															(((distForm.can[scope.row.id+'_'+item.id] || 0) - (distForm.to[scope.row.id+'_'+item.id] || 0)) == 0 ? 
															'满' : '超:'+((distForm.to[scope.row.id+'_'+item.id] || 0) - (distForm.can[scope.row.id+'_'+item.id] || 0)))}}
														</div>
														<div v-show="hasExact"
															class="flex flex-direction justify-center align-center flex-no-wrap text-center margin-lr xs">
															<el-button @click.native="onExact(scope.row.id,item.id)"
																type="text" class="exact-btn">精准选点<span
																	v-if="(distForm.to_exact[scope.row.id+'_'+item.id] || []).length>0">({{(distForm.to_exact[scope.row.id+'_'+item.id] || []).length}})</span>
															</el-button>
															<el-button
																@click.native="onClearExact(scope.row.id,item.id)"
																type="text" class="text-red exact-btn"
																v-if="(distForm.to_exact[scope.row.id+'_'+item.id] || []).length>0">
																清空</el-button>
														</div>
													</div>
												</template>
											</el-table-column>
										</template>
									</el-table>
								</el-form-item>
							</el-col>
						</el-col>
					</el-row>
				</el-card>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click.native="dialogClose('distForm')">取 消</el-button>
				<el-button type="primary" @click.native="onConfirm">确 定</el-button>
			</span>
		</el-dialog>

		<el-dialog :close-on-click-modal="false" title="精准选点(激活设备列表)" center :visible.sync="exactVisible" width="70%"
			@closed="dialogClose('exactTable')">
			<el-table ref="exactTable" :data="exactList" stripe size="mini" tooltip-effect="dark" style="width: 100%;"
				max-height="400" border highlight-current-row :select-on-indeterminate="false"
				@selection-change="handleExactSelectionChange" @select-all="handleExactSelectAll"
				@select="handleExactSelect" row-key="id">
				<el-table-column type="selection" width="50" />
				<el-table-column label="点位" width="120" prop="media_type" />
				<el-table-column label="编号" width="120" prop="code" sortable />
				<el-table-column label="详情" min-width="200">
					<template slot-scope="scope">
						<span v-if="scope.row.media_type_pid==119">{{scope.row.building_number}} 号楼
							{{scope.row.unit_number}} 单元 {{scope.row.floor}} 层</span>
						<span v-else-if="scope.row.media_type_pid==120">
							{{scope.row.door_number}} 号门
							<span v-if="scope.row.media_type_id==135">{{scope.row.rail_number}} 号护栏</span>
						</span>
					</template>
				</el-table-column>
				<el-table-column label="特点" width="120" prop="media_feature" sortable />
			</el-table>
			<div class="margin-tb-xs text-sm">共计<span class="text-green">{{exactTotal || 0}}</span>个空闲，最多可选<span
					class="text-red">{{exactCanChoose>exactTotal?exactTotal:exactCanChoose}}</span>个</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click.native="exactVisible=false;dialogClose('exactTable')">关 闭</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		list_all3rd_bytopcode
	} from '@/api/business/setting/dict'
	import {
		building_area_active_can_devices //可用的激活点位
	} from '@/api/business/building/building'
	import {
		active_list as active_combos //生效中套餐
	} from '@/api/system/combo'
	import common from '@/utils/common.js';
	import {
		isNumber,
		isArray,
		isObject,
		isTrue,
		isFunction,
		generateUUID,
		accMul,
		accAdd,
		accDiv,
		accSub,
		formatDate,
		getTimeSlot
	} from '@/utils/util.js'
	import {
		cloneDeep
	} from 'lodash'
	export default {
		name: 'ChoosedSetting',
		// beforeRouteLeave(to, from, next) {
		// 	this.$destroy();
		// 	next();
		// },
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			hasOneLimt: { // 一层一个限制，仅限电梯媒体
				type: Boolean,
				default: false
			},
			hasFloorLimt: { // 楼层限制，仅限梯外框架（123）、宣传栏媒体（125），1：无；2：地上；3：地下
				type: Boolean,
				default: false
			},
			hasDateRange: {
				type: Boolean,
				default: true
			},
			hasExact: {
				type: Boolean,
				default: true
			},
			hasCombo: {
				type: Boolean,
				default: false
			}
		},
		watch: {},
		computed: {},
		data() {
			return {
				// 显示分配方式切换
				show_dist_type: false,
				// 生效中的套餐
				active_combo_list: [],
				active_combo_map: null,
				// 楼盘可分配数Map
				building_can_map: null,
				// 分配总数
				dist_all_sum: 0,
				// 点位类型
				point_types: [],
				// 电梯媒体
				point_types_dianti: [],
				// 出入口媒体
				point_types_churukou: [],
				// 原始楼盘列表（针对套餐过滤后还原）
				building_areas_origin: [],
				// form
				distForm: {
					dist_type: 1,
					all_combo: {},
					all: {},
					remain_combo: {},
					remain: {},
					distribute_type: '平均分配',
					to_combo: {},
					to: {},
					to_exact: {}, // 精准选点
					can: {},
					all_can: {},
					date_range: ['', ''],
					building_areas: [],
					points_num: {},
					all_points_num: {},
					one_limit: {}, // 一层一个限制，仅限电梯媒体
					floor_limit: {} // 楼层限制，仅限梯外框架（123）、宣传栏媒体（125），1：无；2：地上；3：地下
				},
				columns: {},
				remains: [],

				exactVisible: false,
				exactKey: '',
				exactList: [],
				exactTotal: 0,
				exactCanChoose: 0,
				exactSelects: [],
			}
		},
		mounted() {
			this.getPointTypes()
			this.getActiveCombos()
		},
		methods: {
			// 计算合计套餐剩余数（表格底部行）
			calculSumRemainCombo(comboId = -1) {
				const that = this
				if (that.distForm) {
					for (const idx in (that.distForm.all_combo || {})) {
						let all = (that.distForm.all_combo['' + idx] || 0);
						(that.distForm.building_areas || []).forEach(item => {
							all -= (that.distForm.to_combo[item.id + '_' + idx] || 0)
						})
						that.distForm.remain_combo[idx] = all
					}
					if (comboId != -1) return cloneDeep(that.distForm.remain_combo[comboId] || 0)
				}
			},
			// 平均分配套餐
			equalDistributeCombo() {
				const that = this
				const comboIds = Object.keys(that.distForm.all_combo)

				that.$set(that.distForm, 'to_combo', {})
				that.$set(that.distForm, 'to', {})
				that.$set(that.distForm, 'all', {})

				if (isArray(comboIds) && comboIds.length > 0) {
					comboIds.forEach(c => {
						const cId = parseInt(c)
						const ruleList = that.active_combo_map.get(cId).ruleList
						let ruleMapList = []
						ruleList.forEach(r => {
							const points = r.points
							let pointMap = new Map()
							points.forEach(p => {
								pointMap.set(parseInt(p.point_type_id), parseInt(p.count))
							})
							ruleMapList.push(pointMap)
						})

						const all = parseInt(that.distForm.all_combo[cId] || 0)
						if (all > 0) {
							let flag = true
							let remain = parseInt(all)
							while (remain > 0 && flag) {
								let zeroFlag = false // 一次楼盘循环没有匹配
								for (let x = 0; x < (that.distForm.building_areas || []).length; x++) {
									const b = that.distForm.building_areas[x]
									const bId = parseInt(b.id)
									const pMap = that.building_can_map.get(bId)
									let flagList = []
									ruleMapList.forEach(rMap => {
										let innerFlag = true
										for (const [id, count] of rMap) {
											innerFlag = innerFlag && (((pMap.get(id) || 0) - (that.distForm
												.to[bId + '_' + id] || 0)) >= count)
										}
										flagList.push(innerFlag)
									})
									// console.log('ruleMapList',ruleMapList)
									// console.log('flagList',flagList)
									// 剩余点位数量符合规则
									if (flagList.indexOf(true) != -1) {
										zeroFlag = true
										let i = 0
										for (i = 0; i < flagList.length; i++) {
											if (flagList[i]) break;
										}
										const rMap = ruleMapList[i]
										for (const [id, count] of rMap) {
											that.$set(that.distForm.to, bId + '_' + id, (that.distForm.to[bId +
												'_' + id] || 0) + count)
											that.$set(that.distForm.all, '' + id, (that.distForm.all[id] || 0) +
												count)
										}
										that.$set(that.distForm.to_combo, bId + '_' + cId, (that.distForm.to_combo[
											bId + '_' + cId] || 0) + 1)
										remain--;
									} else {
										if (x >= that.distForm.building_areas.length - 1) {
											if (!zeroFlag) flag = false
										}
									}
									if (remain <= 0) break;
								}
							}
						}

					})
				}
			},
			// 修改某个楼盘套餐数
			changePointToCombo(val, buildingAreaId, comboId) {
				const that = this;
				//精准点位置空
				(Object.keys(that.distForm.to_exact) || []).forEach(key => {
					if (key) {
						let ks = key.split('_')
						if (ks[0] == buildingAreaId) {
							that.distForm.to_exact[key] = []
						}
					}
				});
				// 给当前楼盘，分配的套餐
				let comboMap = new Map();
				(Object.keys(that.distForm.to_combo) || []).forEach(key => {
					let ks = key.split('_')
					if (ks[0] == buildingAreaId && (that.distForm.to_combo[key] || 0) > 0) {
						comboMap.set(parseInt(ks[1]), parseInt(that.distForm.to_combo[key]))
					}
				});
				// 当前楼盘，各点位可分配数
				let _pointMap = that.building_can_map.get(parseInt(buildingAreaId))
				let BpointMap = new Map()
				for(const [pId, pCount] of _pointMap){
					BpointMap.set(pId, pCount)
				}

				// 用套餐分配对应点位
				let toMap = new Map();
				for (const [cId, ccount] of comboMap) {
					let remainCount = parseInt(ccount)
					const ruleList = that.active_combo_map.get(cId).ruleList
					let ruleMapList = []
					ruleList.forEach(r => {
						const points = r.points
						let pointMap = new Map()
						points.forEach(p => {
							pointMap.set(parseInt(p.point_type_id), parseInt(p.count))
						})
						ruleMapList.push(pointMap)
					})
					if (ruleMapList.length == 1) {
						for (const [pId, pcount] of ruleMapList[0]) {
							let toCount = toMap.get(pId) || 0
							toMap.set(pId, parseInt(toCount) + pcount * ccount)
						}
					} else {
						let counts = []
						let toCalMap = new Map()
						for (const pMap of ruleMapList) {
							let curCount = parseInt(remainCount)
							for (const [pId, pcount] of pMap) {
								let count = parseInt(accDiv(accSub(parseInt(BpointMap.get(pId)),parseInt(toCalMap.get(pId) || 0)), parseInt(pcount)))
								if(count > 0){
									if (count < curCount) curCount = parseInt(count)
								}else{
									curCount = 0
								}
							}
							counts.push(curCount)
							for (const [pId, pcount] of pMap) {
								let toCount = toCalMap.get(pId) || 0
								toCalMap.set(pId, (toCount || 0) + pcount * curCount)
								let can = BpointMap.get(pId) || 0
								let curCan = parseInt(can) - pcount * curCount
								BpointMap.set(pId, curCan>0?curCan:0)
							}
							remainCount -= curCount
						}
						let sumCount = 0
						for (let c of counts) {
							sumCount += c
						}
						if (sumCount < ccount) {
							counts[0] += parseInt(ccount - sumCount)
						}
						for (let i = 0; i < ruleMapList.length; i++) {
							if((counts[i] || 0)>0){
								const pMap = ruleMapList[i]
								for (const [pId, pcount] of ruleMapList[i]) {
									let toCount = toMap.get(pId) || 0
									toMap.set(pId, parseInt(toCount) + pcount * counts[i])
								}
							}
						}
					}
				}
				console.log(toMap)

				// 重新合计总套餐数
				let allComboMap = new Map()
				for(const key of (Object.keys(that.distForm.to_combo) || [])){
					if(key){
						let ks = key.split('_')
						let cId = parseInt(ks[1])
						let count = allComboMap.get(cId) || 0
						allComboMap.set(cId, parseInt(accAdd(count ,(that.distForm.to_combo[key] || 0))))
					}
				}
				for(const [cId, ccount] of allComboMap){
					that.$set(that.distForm.all_combo,''+cId, parseInt(ccount))
				}
				
				// 重新合计点位分配数和总数
				for(const [pId, pcount] of toMap){
					that.$set(that.distForm.to,buildingAreaId+'_'+pId, parseInt(pcount))
				}
				let allMap = new Map()
				for(const key of (Object.keys(that.distForm.to) || [])){
					if(key){
						let ks = key.split('_')
						let pId = parseInt(ks[1])
						let count = allMap.get(pId) || 0
						allMap.set(pId, parseInt(accAdd(count,(that.distForm.to[key] || 0))))
					}
				}
				for(const [pId, pcount] of allMap){
					that.$set(that.distForm.all,''+pId, parseInt(pcount))
				}
				

			},
			// 修改套餐总数，过滤符合套餐规则的楼盘
			changePointAllCombo(val, comboId) {
				const that = this
				that.$set(that.distForm, 'building_areas', [])
				that.filterComboCanBuildings()
				switch (that.distForm.distribute_type) {
					case '平均分配':
						that.equalDistributeCombo()
						break
				}
			},
			// 过滤符合套餐规则的楼盘
			filterComboCanBuildings() {
				const that = this
				const comboIds = Object.keys(that.distForm.all_combo)

				let noDistCombo = true
				if (!comboIds || comboIds.length <= 0) noDistCombo = true
				if (isArray(comboIds) && comboIds.length > 0) {
					comboIds.forEach(c => {
						const cId = parseInt(c)
						noDistCombo = noDistCombo && (parseInt(that.distForm.all_combo[cId] || 0) == 0)
					})
				}

				if (noDistCombo) {
					that.$set(that.distForm, 'building_areas', JSON.parse(JSON.stringify(that.building_areas_origin)))
				} else {
					let rules = []
					comboIds.forEach(c => {
						const cId = parseInt(c)
						if (parseInt(that.distForm.all_combo[cId] || 0) > 0) {
							let combo = that.active_combo_map.get(cId)
							let ruleList = combo.ruleList
							rules = rules.concat(ruleList)
						}
					})

					if (rules.length > 0) {
						let bIdSet = new Set()
						rules.forEach(r => {
							const points = r.points
							let pointMap = new Map()
							points.forEach(p => {
								pointMap.set(parseInt(p.point_type_id), parseInt(p.count))
							})
							that.building_areas_origin.forEach(b => {
								const bId = parseInt(b.id)
								const pMap = that.building_can_map.get(bId)
								let flag = true
								for (const [id, count] of pointMap) {
									flag = flag && (pMap.get(id) >= count)
								}
								if (flag) bIdSet.add(bId)
							})
						})
						let rBuildings = []
						if (bIdSet.size > 0) {
							that.building_areas_origin.forEach(b => {
								const bId = parseInt(b.id)
								if (bIdSet.has(bId))
									rBuildings.push(JSON.parse(JSON.stringify(b)))
							})
						}
						that.$set(that.distForm, 'building_areas', rBuildings)
					}
				}
			},
			// 重新组装楼盘可用点位数，用于分配套餐
			getBuildingCanMap() {
				const that = this
				let resultMap = new Map()
				if (that.distForm.can) {
					const keys = Object.keys(that.distForm.can)
					if (keys) {
						for (const key of keys) {
							let ks = key.split('_')
							let b = resultMap.get(parseInt(ks[0]))
							if (!b) {
								b = new Map()
							}
							let count = parseInt(that.distForm.can[key] || 0)
							if (count > 0) b.set(parseInt(ks[1]), count)
							resultMap.set(parseInt(ks[0]), b)
						}

					}
				}
				that.building_can_map = resultMap
			},
			// 获取所有套餐
			getActiveCombos() {
				const that = this
				active_combos()
					.then(({
						data
					}) => {
						if (data.length > 0) {
							that.show_dist_type = true
							that.active_combo_list = data
							that.active_combo_map = new Map()
							data.forEach(d => {
								that.active_combo_map.set(parseInt(d.id), d)
							})
						}
					})
			},
			// 改变分配方式
			changeDistType(val) {
				const that = this
				that.$set(that.distForm, 'to', {})
				that.$set(that.distForm, 'all', {})
				that.$set(that.distForm, 'to_combo', {})
				that.$set(that.distForm, 'all_combo', {})
				if (val == 1) {
					that.$set(that.distForm, 'building_areas', JSON.parse(JSON.stringify(that.building_areas_origin)))
				}
				if (val == 2) {
					that.building_areas_origin = JSON.parse(JSON.stringify(that.distForm.building_areas))
					that.getBuildingCanMap()
					switch (that.distForm.distribute_type) {
						case '平均分配':
							that.equalDistribute()
							break
					}
					that.calDistAllSum()
				}
			},


			// 精准选点
			onExact(buildingId, pointTypeId) {
				const that = this
				building_area_active_can_devices({
					id: buildingId,
					point_type_id: pointTypeId,
					start_at: that.distForm.date_range[0],
					end_at: that.distForm.date_range[1]
				}).then(({
					data
				}) => {
					that.exactKey = buildingId + '_' + pointTypeId
					that.exactList = cloneDeep(data || [])
					that.exactTotal = data.length || 0
					that.exactCanChoose = that.distForm.can[that.exactKey] || 0
					that.exactVisible = true
					that.$nextTick(() => {
						that.toggleSelection()
					})

				})
			},
			// 清空精准选点
			onClearExact(buildingId, pointTypeId) {
				const that = this
				let key = buildingId + '_' + pointTypeId
				that.$set(that.distForm.to_exact, key, [])
			},
			// 处理勾选， 判断总数是否大于限制数
			handleExactSelectedOverCan(selection, row) {
				const that = this
				if (selection && isArray(selection)) {
					const sLen = parseInt(selection.length)
					if (selection.length > that.exactCanChoose) {
						if (row) {
							that.$refs.exactTable.toggleRowSelection(row, false);
							common.messageError('不允许勾选超出' + that.exactCanChoose + '个设备！')
						} else {
							for (let i = parseInt(that.exactCanChoose); i < sLen; i++) {
								let row = that.exactList[i];
								that.$refs.exactTable.toggleRowSelection(row, false);
							}
							common.messageSuccess('已勾选' + that.exactCanChoose + '个设备')
						}
					}
				}
			},
			// 全部勾选
			handleExactSelectAll(selection) {
				const that = this
				that.handleExactSelectedOverCan(selection)
			},
			// 勾选一行
			handleExactSelect(selection, row) {
				const that = this
				that.handleExactSelectedOverCan(selection, row)
			},
			// 表格多选
			handleExactSelectionChange(val) {
				const that = this
				that.$set(that.distForm.to_exact, that.exactKey, val)
				that.distForm.to[that.exactKey] = val.length <= that.distForm.to[that.exactKey] ? that.distForm.to[that
					.exactKey] : (val.length || 0)
			},
			toggleSelection() {
				const that = this
				if (that.exactList && isArray(that.exactList) &&
					that.distForm.to_exact[that.exactKey] && isArray(that.distForm.to_exact[that.exactKey])) {
					let idSet = new Set();
					that.distForm.to_exact[that.exactKey].forEach(item => {
						idSet.add('' + item.id)
					})
					that.exactList.forEach(row => {
						if (idSet.has('' + row.id)) that.$refs.exactTable.toggleRowSelection(row);
					});
				} else {
					that.$refs.exactTable.clearSelection();
				}
			},
			// 重置精准选点相关数据
			resetExactList() {
				const that = this
				that.exactKey = ''
				that.exactList = []
				that.exactTotal = 0
				that.exactCanChoose = 0
				that.exactSelects = []
			},
			// 初始化数据
			initDistForm(info) {
				this.distForm = Object.assign({
					dist_type: 1,
					all_combo: {},
					all: {},
					remain_combo: {},
					remain: {},
					distribute_type: '平均分配',
					to_combo: {},
					to: {},
					to_exact: {}, // 精准选点
					can: {},
					all_can: {},
					date_range: ['', ''],
					building_areas: [],
					points_num: {},
					all_points_num: {},
					one_limit: {},
					floor_limit: {}
				}, info)
			},
			// 关闭
			dialogClose(formName) {
				const that = this
				switch (formName) {
					case 'distForm':
						that.distForm = {
							dist_type: 1,
							all_combo: {},
							all: {},
							remain_combo: {},
							remain: {},
							distribute_type: '平均分配',
							to_combo: {},
							to: {},
							to_exact: {}, // 精准选点
							can: {},
							all_can: {},
							date_range: ['', ''],
							building_areas: [],
							points_num: {},
							all_points_num: {},
							one_limit: {},
							floor_limit: {}
						};
						that.$emit('update:visible', false);
						break;
					case 'exactTable':
						that.resetExactList();
						break;
				}

			},
			// 检查分配数量大于可用数的，进行二次确认
			checkNum() {
				const that = this
				const to = cloneDeep(that.distForm.to)
				const can = cloneDeep(that.distForm.can)

				return new Promise(async (resolve, reject) => {
					let flag = true
					let to_sum = 0
					for (const idx of Object.keys(to)) {
						if (parseInt(to[idx] || 0) > 0) {
							const to_num = parseInt(to[idx] || 0)
							to_sum += parseInt(to[idx] || 0)
							const can_num = parseInt(can[idx] || 0)
							if (can_num < to_num) flag = false
						}
					}
					if (!flag) {
						const confirm = await common.confirmDialog('存在分配数超出可用数，您确认吗？')
						resolve(confirm)
					} else if (to_sum == 0) {
						await common.messageError('未分配任何点位！')
						resolve(false)
					} else {
						resolve(true)
					}
				})
			},
			checkReamins() {
				const that = this
				return new Promise((resolve, reject) => {
					if (that.remains && isArray(that.remains) && that.remains.length > 0) {
						let flag = true
						that.remains.forEach(item => {
							flag = flag && !isNumber(item)
						})
						resolve(flag)
					} else {
						resolve(true)
					}
				})

			},
			// 确定
			async onConfirm() {
				const that = this
				const remainCheck = await that.checkReamins()
				if (!remainCheck) {
					common.messageError('请检查剩余数，未分配完全！')
					return false
				}
				const confirm = await that.checkNum()
				if (confirm) {
					that.$emit('on-confirm', that.generateSettingInfo())
				}
			},
			generateSettingInfo() {
				const that = this
				const exactKeys = Object.keys(that.distForm.to_exact)
				let exact = {}
				for (let key of exactKeys) {
					if (key) exact[key] = cloneDeep(that.distForm.to_exact[key])
				}
				let returnData = {
					to: that.distForm.to,
					to_exact: exact,
					uuid: {},
					date_range: that.distForm.date_range,
					building_areas: that.distForm.building_areas.map(item => ({
						id: item.id,
						name: item.name
					})),
					one_limit: cloneDeep(that.distForm.one_limit),
					floor_limit: cloneDeep(that.distForm.floor_limit),
					point_types: []
				}

				for (const key of Object.keys(returnData.to)) {
					returnData.uuid[key] = generateUUID()
				}


				const buildingsFlag = that.distForm.building_areas && isArray(that.distForm.building_areas) && that
					.distForm.building_areas.length > 0,
					pointTypesFlag = that.point_types && isArray(that.point_types) && that.point_types.length > 0

				if (buildingsFlag && pointTypesFlag) {

					let overZeroPointTypes = {}
					for (const idx of Object.keys(that.distForm.all || {})) {
						if (parseInt(that.distForm.all[idx] - 0) > 0) overZeroPointTypes[idx] = true
					}

					(that.point_types || []).forEach(item => {
						if (overZeroPointTypes[item.id]) returnData.point_types.push({
							id: item.id,
							name: item.name
						})
					})

				}

				return returnData
			},
			// 获取点位类型
			getPointTypes() {
				const that = this
				return list_all3rd_bytopcode({
						code: 'dwxg'
					})
					.then(res => {
						const {
							code,
							data
						} = res
						if (code == 200) {
							that.point_types_dianti = []
							that.point_types_churukou = []
							that.point_types = data
							data.forEach(item => {
								if (item.code.indexOf('dwxg-dtmt') != -1) {
									that.point_types_dianti.push(cloneDeep(item))
									that.distForm.one_limit[item.id] = false
									that.distForm.floor_limit[item.id] = 1
								} else {
									that.point_types_churukou.push(cloneDeep(item))
								}
							})
						}
					})
			},
			// 改变锁定规则
			async changeDistributeType(val) {
				const that = this
				switch (val) {
					case '平均分配':
						that.equalDistribute()
						break
				}
			},
			// 显示剩余数
			getRemain(param) {
				const that = this
				const {
					columns,
					data
				} = param;
				const remains = [];
				columns.forEach((column, index) => {
					//if ((columns.length - 1) == index) column.type='sum'
					if (index === 0) {
						remains[index] = '剩余待分配';
						return;
					} else if (column.property && column.property.indexOf('combo_') != -1) {
						const rem = that.calculSumRemainCombo(column.index)
						if (rem == 0) {
							remains[index] = '分配完全';
						} else {
							remains[index] = parseInt(rem);
						}
						return;
					} else if (column.property !== 'all_unit' && column.property !== 'all_door') {
						const rem = that.calculSumRemain(column.index)
						if (rem == 0) {
							remains[index] = '分配完全';
						} else {
							remains[index] = parseInt(rem);
						}
						return;
					}
				});

				that.remains = cloneDeep(remains)

				return remains;
			},
			generateRemainTip(buildingId, pointId) {
				const key = buildingId + '_' + pointId
				const can = (this.distForm.can[key] || 0)
				const to = (distForm.to[key] || 0)
				const remain = can - to
				if (remain > 0) {
					return {
						type: 1,
						tip: ('余:' + remain)
					}
				} else if (remain == 0) {
					return {
						type: 2,
						tip: '满'
					}
				} else {
					return {
						type: 3,
						tip: '超:' + (-remain)
					}
				}
			},
			calDistAllSum() {
				const that = this
				let sum = 0
				let keys = Object.keys(that.distForm.all)
				if (isArray(keys) && keys.length > 0) {
					keys.forEach(key => {
						sum += parseInt(that.distForm.all[parseInt(key)] || 0)
					})
				}
				that.dist_all_sum = sum
			},
			// 改变点位总数
			async changePointAll(val, pointId) {
				const that = this
				switch (that.distForm.distribute_type) {
					case '平均分配':
						that.equalDistribute()
						break
				}
				that.calDistAllSum()
			},
			// 计算合计点位剩余数（表格底部行）
			calculSumRemain(pointId = -1) {
				const that = this
				if (that.distForm) {
					for (const idx in (that.distForm.all || {})) {
						let all = (that.distForm.all['' + idx] || 0);
						(that.distForm.building_areas || []).forEach(item => {
							all -= (that.distForm.to[item.id + '_' + idx] || 0)
						})
						that.distForm.remain[idx] = all;
					}
					if (pointId != -1) return cloneDeep(that.distForm.remain[pointId] || 0)
				}
			},
			// 平均分配
			equalDistribute() {
				const that = this
				// 点位类型ids
				let pointIds = [];
				for (const pointId of Object.keys(cloneDeep(that.distForm.all || {}))) {
					pointIds.push(pointId)
				}
				// 楼盘ids
				const buildingIds = (that.distForm.building_areas || []).map(item => {
					return item.id
				})

				if (buildingIds.length > 0 && pointIds.length > 0) {
					let results = {}
					// for (const index in that.distForm.can) {
					// 	results[index] = {
					// 		can: that.distForm.can[index] - 0,
					// 		to: 0
					// 	}
					// }
					buildingIds.forEach(buildingId => {
						pointIds.forEach(pointId => {
							let index = buildingId + '_' + pointId
							results[index] = {
								can: that.distForm.can[index] - 0,
								to: 0
							}
						})
					})
					pointIds.forEach(pointId => {
						let to_add_point = that.distForm.all[pointId] || 0
						let flag = true
						while (to_add_point > 0 && flag) {
							flag = false
							buildingIds.forEach(buildingId => {
								const can = parseInt(results[buildingId + '_' + pointId].can ||
									0)
								let to = parseInt(results[buildingId + '_' + pointId].to || 0)
								if (to_add_point > 0 && can > to) {
									flag = true
									results[buildingId + '_' + pointId].to = (++to)
									to_add_point--
								}
							})
						}

					})
					//console.log(results)

					for (const index in results) {
						that.distForm.to[index] = results[index].to
					}

					that.calculSumRemain(-1)
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	/deep/.el-table__fixed-footer-wrapper {
		font-weight: bold !important;
	}

	.point-all-card {
		/deep/.el-card__body {
			padding: 10px 15px 10px 5px;

			.el-form-item.el-form-item--small {
				margin: 5px 0;
			}
		}
	}

	/deep/.el-input-group__append {
		padding: 0 10px !important;
	}

	/deep/.el-button.el-button--text.el-button--mini.exact-btn {
		padding: 1px 0 !important;
		margin: 0 !important;
	}

	.top-right-box {
		position: absolute;
		right: 20px;
		top: 20px;
		z-index: 2;
	}

	/deep/.check-dialog-title-box {
		position: relative;
		height: 32px;
		line-height: 32px;
		padding: 0;

		.check-dialog-close-btn {
			position: absolute;
			top: 0;
			bottom: 0;
			right: 20px;
		}
	}

	/deep/.combo-rule {
		word-wrap: break-word;
		word-break: break-all;
		white-space: pre-wrap !important;
		background-color: #fff;
		color: #1890ff;
		padding: 0 5px;
		line-height: 19px;
		border-radius: 5px;
		border: 1px solid #a3d3ff;
		font-size: 12px;
	}
</style>
